package com.thzy.bbs.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.thzy.bbs.R;
import com.thzy.bbs.common.AddressConfig;
import com.thzy.bbs.common.CommonUtils;
import com.thzy.bbs.common.Constants;
import com.thzy.bbs.common.HttpRequestUtils;
import com.thzy.bbs.thread.DownApkThread;

import org.xutils.http.HttpMethod;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import static android.content.DialogInterface.BUTTON_NEGATIVE;
import static android.content.DialogInterface.BUTTON_POSITIVE;

/**
 * 启动页面
 */
@ContentView(R.layout.activity_start)
public class StartActivity extends AppCompatActivity {
    @ViewInject(R.id.start_image)
    private ImageView imageView;
    /**
     * 提示框
     */
    private ProgressDialog progressDialog;
    /**
     * 下载地址
     */
    private String url;
    /**
     * app名称
     */
    private String name;
    /**
     * 更新信息
     */
    private String updateInfo;

    /**
     * 是否需要强制更新
     */
    private Boolean isConstraint;


    private static final String KEY_GUIDE_ACTIVITY = "start_activity";
    /**
     * 判断你是否第一次进入app
     */
    private boolean isFirstEnter;

    /**
     * 消息接收
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String applicationPath = CommonUtils.getApplicationPath(StartActivity.this);
            switch (msg.what) {
                case Constants.HandlerCode.HAVE_NEW:
                    progressDialog = new ProgressDialog(StartActivity.this);
                    //检测到有新版本,是否更新？
                    progressDialog.setTitle(R.string.have_update);
                    progressDialog.setMessage(updateInfo);
                    //更新
                    progressDialog.setButton(BUTTON_NEGATIVE, StartActivity.this.getString(R.string.update), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mHandler.sendEmptyMessage(Constants.HandlerCode.DOWN_APK);
                        }
                    });
                    //非强制更新允许取消：取消
                    progressDialog.setButton(BUTTON_POSITIVE, StartActivity.this.getString(R.string.batal), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (isConstraint) {
                                progressDialog.dismiss();
                                StartActivity.this.finish();
                                return;
                            }
                            mHandler.sendEmptyMessage(Constants.HandlerCode.NEXT);
                        }
                    });
                    progressDialog.setCancelable(false);
                    progressDialog.show();
                    return;
                case Constants.HandlerCode.DOWN_APK:
                    //存在更新显示提示框
                    progressDialog = new ProgressDialog(StartActivity.this);
                    progressDialog.setCancelable(false);
                    progressDialog.setTitle(StartActivity.this.getString(R.string.mengunduh));//正在下载
                    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    progressDialog.setCancelable(false);
                    progressDialog.show();
                    new DownApkThread(progressDialog, mHandler, url, name, applicationPath).start();
                    return;
                case Constants.HandlerCode.UPDATE://下载成功
                    // 通过Intent安装APK文件
                    File file = new File(CommonUtils.getSDPath() + "/", name);
                    if (!file.exists()) {
                        progressDialog.dismiss();
                        //没找到安装包
                        progressDialog.setTitle(StartActivity.this.getString(R.string.install));
                        return;
                    }
                    Intent intent = new Intent();
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction(android.content.Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(file),
                            "application/vnd.android.package-archive");
                    startActivity(intent);
                    finish();
                    return;
                case Constants.HandlerCode.ERROR_DOWN:
                    progressDialog.dismiss();
                    progressDialog = new ProgressDialog(StartActivity.this);
                    //下载失败
                    progressDialog.setTitle(StartActivity.this.getString(R.string.mengunduh));
                    //重新下载
                    progressDialog.setMessage(StartActivity.this.getString(R.string.ulang));
                    //下载
                    progressDialog.setButton(BUTTON_NEGATIVE, StartActivity.this.getString(R.string.mengunduh), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mHandler.sendEmptyMessage(Constants.HandlerCode.DOWN_APK);
                        }
                    });
                    //取消
                    progressDialog.setButton(BUTTON_POSITIVE, StartActivity.this.getString(R.string.batal), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (isConstraint) {
                                progressDialog.dismiss();
                                mHandler.sendEmptyMessage(Constants.HandlerCode.FINASH);
                                return;
                            }
                            mHandler.sendEmptyMessage(Constants.HandlerCode.NEXT);
                        }
                    });
                    progressDialog.show();
                    return;
                case Constants.HandlerCode.NEXT://不存在更新，进入下个页面
                    next();
                    return;
                case Constants.HandlerCode.FINASH:
                    progressDialog.dismiss();
                    StartActivity.this.finish();
                default:
                    super.handleMessage(msg);
            }
        }

        /**
         * 页面跳转
         */
        private void next() {
            Intent intent;
            if (isFirstEnter) {
                intent = new Intent(StartActivity.this, LoginActivity.class);
                SharedPreferences.Editor editor = StartActivity.this.getSharedPreferences(KEY_GUIDE_ACTIVITY, 0).edit();
                editor.putBoolean(KEY_GUIDE_ACTIVITY, false);
                editor.commit();
            } else {
                intent = new Intent(StartActivity.this, MainActivity.class);
            }
            startActivity(intent);
            finish();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        x.view().inject(this);
        x.Ext.init(this.getApplication());//初始化xUtils
        Glide.with(this).load(R.drawable.guide).into(imageView);
        isFirstEnter();
        findVersion();

    }

    /**
     * 获取更新
     */
    private void findVersion() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                super.run();
                String result;
                int localVersion = CommonUtils.getVersionCode(StartActivity.this);
                Map<String, Object> params = new HashMap<>(1);
                params.put("version", localVersion);
                try {
                    result = HttpRequestUtils.sendSynchronous(HttpMethod.GET, AddressConfig.ConfigAddress.APK_INFO, null, params,
                            4000, false);
                } catch (Throwable throwable) {
                    mHandler.sendEmptyMessageDelayed(Constants.HandlerCode.NEXT, 2000);
                    return;
                }
                JSONObject jsonObject = JSON.parseObject(result);
                if (!jsonObject.getBoolean("success")) {
                    mHandler.sendEmptyMessage(Constants.HandlerCode.NEXT);
                    return;
                }
                JSONObject data = jsonObject.getJSONObject("data");
                Boolean update = data.getBoolean("isUpdate");
                url = data.getString("url");
                name = data.getString("name") + ".apk";
                updateInfo = data.getString("info");
                isConstraint = data.getBoolean("constraint");
                if (!update) {
                    mHandler.sendEmptyMessageDelayed(Constants.HandlerCode.NEXT, 3000);
                    return;
                }
                mHandler.sendEmptyMessage(Constants.HandlerCode.HAVE_NEW);
            }
        };
        thread.start();
    }

    /**
     * 判断是否第一次进入
     *
     * @return
     */
    private void isFirstEnter() {
        SharedPreferences pref = this.getSharedPreferences(KEY_GUIDE_ACTIVITY, 0);
        boolean mResultStr = pref.getBoolean(KEY_GUIDE_ACTIVITY, true);
        isFirstEnter = mResultStr;
    }
}
